package xjay.ai.emotionalsupport.chatmemory;

import jakarta.annotation.Resource;
import org.springframework.ai.chat.messages.Message;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ChatHistoryService {

    @Resource(name = "jdbcChatMemoryRepository")
    private JdbcChatMemoryRepository chatMemoryRepository;

    /**
     * note: 历史会话提取
     * @param userId
     * @param sessionId
     * @return
     */
    public List<Message> contextMessages(String userId, String sessionId) {
        // 实现智能上下文构建逻辑
        List<Message> contextMessages = new ArrayList<>();
        Long maxOrder = chatMemoryRepository.getMaxOrder(userId, sessionId);

        //maxOrder按理来讲，应该从1开始，且为偶数
        for(int i = 1; i <= maxOrder; i++) {
            Message message = chatMemoryRepository.getMessage(userId, sessionId, i);
            contextMessages.add(message);
        }

        return contextMessages;
    }

    public void insertQA(String userId, String sessionId, String userMessage, String assistantMessage) {
        chatMemoryRepository.insertMessage(userId, sessionId, userMessage, true);
        chatMemoryRepository.insertMessage(userId, sessionId, assistantMessage, false);

    }

}
